local sort_list = class("SortList"){
    root = nil;
    tail = nil;
    count = 0;
    sort_node_table = {};
}

function sort_list:__init__()
    self.root = {};
    self.tail = self.root;
end

function sort_list:add(z_index,object)
    if self.sort_node_table[object] ~= nil then
        return false
    end
    local node = {data = object,z_index = z_index}

    local fnode = self:find_inode(function(node)
        return node.z_index >= z_index
    end)

    if fnode == nil then
        self.tail._next = node
        node._up = self.tail
        self.tail = node
    else  
        fnode._up._next = node
        node._up = fnode._up
        node._next = fnode
        fnode._up = node
    end

    self.sort_node_table[object] = node
    self.count = self.count + 1
    return true
end

function sort_list:remove(object)
    local node = self.sort_node_table[object];
    if node then
        self.sort_node_table[object] = nil
        local up = node._up
        local next = node._next

        up._next = next;
        if next ~= nil then
            next._up = up;
        else
            self.tail = up;
        end
        self.count = self.count - 1
        return true
    end
    return false
end

function sort_list:find_inode(c)--正向寻找
    local node = self.root._next;
    while node ~= nil do
        if c(node) then
            return node;
        end
        node = node._next;
    end
    return nil;
end

function sort_list:dnif_inode(c)--反向寻找
    local node = self.tail;
    while node ~= self.root do
        if c(node) then
            return node;
        end
        node = node._up;
    end
    return nil;--表示找不到
end

function sort_list:items()
    local node = self.root._next;
    return function()
        if node == nil then
            return nil
        end
        local rnode = node;
        node = node._next;
        return rnode;
    end
end

return sort_list